<html>
<head>
<title>FeedGraph Chat Demo</title>
<script src="http://www.feedgraph.com/js/feedgraph.js"></script>
<script>

var msgsdiv = null;
var you = "anonymous";

function prettyTime(time) {

	var today = new Date();
	var time = new Date(Date.parse(time));

	if (today.toDateString() == time.toDateString()) {
		return time.toLocaleTimeString();
	}

	return time.toUTCString();
}

function updateOnUser(obj, meta) {

	writeMessage("<i>" + sanitize(obj.User) + " signed on at " + prettyTime(meta.CreatedAt) + "</i>");
}

function updateOffUser(obj, meta) {

	writeMessage("<i>" + sanitize(obj.User) + " signed off at " + prettyTime(meta.CreatedAt) + "</i>");
}

function updateMessage(obj, meta) {

	writeMessage(prettyTime(meta.CreatedAt) + " " + sanitize(obj.From) + ": " + sanitize(obj.Text));
}

function writeMessage(msg) {

	var span = document.createElement("span");
	span.innerHTML = msg;
	msgsdiv.appendChild(span);
	msgsdiv.appendChild(document.createElement("br"));
}

function init() {

	
	msgsdiv = document.getElementById("msgsdiv");
	sayinput = document.getElementById("sayinput");

	feedgraph.postobj("/chat/USERS/signed_on", {"User": you});
	feedgraph.watch("/chat/MESSAGES/public", updateMessage);
	feedgraph.watch("/chat/USERS/signed_off", updateOffUser, true);
	feedgraph.watch("/chat/USERS/signed_on", updateOnUser, true);
}

function changeName() {

	feedgraph.postobj("/chat/USERS/signed_off", {"User": you}); 

	you = document.getElementById("you").value;

	feedgraph.postobj("/chat/USERS/signed_on", {"User": you});
}

function say() {

	feedgraph.postobj("/chat/MESSAGES/public", {"From":you, "Text": sayinput.value});
	sayinput.value = "";
}

function sanitize(str) {

	if (!str) return "";

	return str.replace(/[<>]/g,"");
}

</script>
</head>
<body onload=init()>
<label>signed in as:</label>
<input id=you type=text value="anonyomous" onchange="changeName()"/>
<br><label>messages:</label>
<div id=msgsdiv>
</div>
<label>say:</label>
<input id=sayinput type=text onchange="say()"/>
</body>
</html>
